package com.smile.frame.seckill.core.queqe;

import com.smile.frame.common.result.Result;
import com.smile.frame.seckill.service.SecondKillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author LGC
 */ // 消费秒杀队列
@Slf4j
@Component
public class TaskRunner implements ApplicationRunner {

    @Autowired
    private SecondKillService seckillService;

//    消费秒杀队列中调用业务方法加锁与不加锁情况一样，也就是seckillService.startSecondKillByAop()、seckillService.startSecondKillByLock()方法结果一样，这也很好理解
//    当队列长度与商品数量一致时，会出现少卖的现象，可以调大数值
//    下面是队列长度1000，商品数量1000，并发数2000情况下出现的少卖

    @Override
    public void run(ApplicationArguments var) {
        new Thread(() -> {
            log.info("队列启动成功");
            while (true) {
                try {
                    // 进程内队列
                    TradeSecKillOrderCreateReq kill = SecondKillQueue.getSkillQueue().consume();
                    if (kill != null) {
                        boolean result = seckillService.startSecondKillByLock(kill.getActivityId(), kill.getUserId());
                        if (result) {
                            log.info("TaskRunner从消息队列取出用户，用户:{}{}", kill.getUserId(), "秒杀成功");
                        }else{
                            log.info("TaskRunner从消息队列取出用户，用户:{}{}", kill.getUserId(), "秒杀失败");
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}